import http from './request'
import { EventSourcePolyfill } from 'event-source-polyfill'

/**
 * AI聊天接口
 * @param {Object} data 包含消息内容和用户ID
 * @returns Promise
 */
export function chatWithAI(data) {
    return http.get('/ai/fluxChat', {
        params: {
            msg: data.message
        }
    })
}

// export function sseConnect() {
//     const token = localStorage.getItem('token');
//     let source;
    
//     if (typeof EventSourcePolyfill !== 'undefined') {
//         source = new EventSourcePolyfill('http://localhost:8080/api/sse/connect', {
//             headers: { 'token': token },
//             withCredentials: true
//         });
//     } else {
//         const baseUrl = new URL('http://localhost:8080/api/sse/connect');
//         baseUrl.searchParams.append('token', token);
//         source = new EventSource(baseUrl.toString(), { 
//             withCredentials: true 
//         });
//     }
    
//     return source;
// }

export function sseConnect() {
    const token = localStorage.getItem('token');
    let source;

    try {
        if (typeof EventSourcePolyfill !== 'undefined') {
            source = new EventSourcePolyfill('http://localhost:8080/api/sse/connect', {
                headers: { 'token': token },
                withCredentials: true,
                heartbeatTimeout: 600000, // 10m timeout
                connectionTimeout: 600000, // 10m timeout
            });

            // 添加消息处理错误捕获
            source.onmessage = async (event) => {
                try {
                    const data = JSON.parse(event.data);
                    // 确保异步操作完成后再处理下一条消息
                    await Promise.resolve(data);
                } catch (error) {
                    console.error('消息解析错误:', error);
                }
            };

            // 添加错误处理和重连机制
            source.onerror = (error) => {
                console.error('SSE连接错误:', error);
                if (source.readyState === EventSource.CLOSED) {
                    // 确保在重连之前完成所有pending的操作
                    Promise.resolve().then(() => {
                        setTimeout(() => {
                            if (source) {
                                source.close();
                                sseConnect();
                            }
                        }, 3000);
                    });
                }
            };

            // 添加连接打开的处理
            source.onopen = () => {
                console.log('SSE连接已建立');
            };

            // 添加页面卸载前的清理
            window.addEventListener('beforeunload', () => {
                if (source) {
                    source.close();
                }
            });

        } else {
            const baseUrl = new URL('http://localhost:8080/api/sse/connect');
            baseUrl.searchParams.append('token', token);
            source = new EventSource(baseUrl.toString(), {
                withCredentials: true
            });

            // 为原生EventSource添加相同的事件处理
            source.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);
                    // 直接处理数据，不需要异步等待
                    return false; // 明确表示同步处理完成
                } catch (error) {
                    console.error('消息解析错误:', error);
                    return false;
                }
            };

            source.onerror = (error) => {
                console.error('SSE连接错误:', error);
                if (source.readyState === EventSource.CLOSED) {
                    setTimeout(() => {
                        if (source) {
                            source.close();
                            sseConnect();
                        }
                    }, 3000);
                }
            };

            source.onopen = () => {
                console.log('SSE连接已建立');
            };
        }

        return source;
    } catch (error) {
        console.error('创建SSE连接失败:', error);
        throw error;
    }
}

export function getHistory() {
    return http.get('/ai/getMsg')
}

export function uploadFile(file) {
    return http.post("/file-analysis/upload", file, {
        timeout: 120000,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

export function getXmind() {
    return http.get("/files/2043fe80-9241-4d85-b5cf-b7a49f872abf_mind-map_1746538777174.xmind")
}

export function generateQuestion(materialId) {
    return http.post("/ai/getQuestion", {
        params: {
            materialId: materialId
        }
    }) 
}